import SwiftUI

// MARK: - 实时咀嚼检测测试视图

struct RealtimeTestView: View {
    
    // MARK: - 状态对象
    
    @StateObject private var sensorRecorder = SensorRecorder()
    @StateObject private var detector: RealtimeChewingDetector
    
    // MARK: - 视图状态
    
    @State private var isRecording = false
    @State private var showAlert = false
    @State private var alertMessage = ""
    
    // MARK: - 初始化
    
    init() {
        // 加载模型（确保模型文件已添加到Xcode项目）
        guard let modelURL = Bundle.main.url(forResource: "ChewingDetector", withExtension: "mlmodelc") else {
            fatalError("❌ 未找到模型文件 ChewingDetector.mlmodelc")
        }
        
        guard let detector = RealtimeChewingDetector(modelURL: modelURL) else {
            fatalError("❌ 模型初始化失败")
        }
        
        _detector = StateObject(wrappedValue: detector)
    }
    
    // MARK: - 视图主体
    
    var body: some View {
        NavigationView {
            ScrollView {
                VStack(spacing: 20) {
                    
                    // MARK: - 检测状态卡片
                    
                    detectionStatusCard
                    
                    // MARK: - 统计信息卡片
                    
                    statisticsCard
                    
                    // MARK: - 传感器数据卡片
                    
                    sensorDataCard
                    
                    // MARK: - 控制按钮
                    
                    controlButtons
                    
                    // MARK: - 实时图表
                    
                    realtimeCharts
                }
                .padding()
            }
            .navigationTitle("🍴 咀嚼检测测试")
            .navigationBarTitleDisplayMode(.inline)
            .alert("提示", isPresented: $showAlert) {
                Button("确定", role: .cancel) { }
            } message: {
                Text(alertMessage)
            }
        }
        .onChange(of: sensorRecorder.currentAccX) { _ in
            // 每次收到新数据就处理
            if isRecording {
                processNewSample()
            }
        }
    }
    
    // MARK: - 子视图组件
    
    /// 检测状态卡片
    private var detectionStatusCard: some View {
        VStack(spacing: 15) {
            // 大图标
            Image(systemName: detector.isChewing ? "fork.knife.circle.fill" : "circle")
                .font(.system(size: 80))
                .foregroundColor(detector.isChewing ? .green : .gray)
                .animation(.spring(), value: detector.isChewing)
            
            // 状态文本
            Text(detector.statusText)
                .font(.title2)
                .fontWeight(.bold)
                .foregroundColor(detector.isChewing ? .green : .secondary)
            
            // 概率条
            VStack(alignment: .leading, spacing: 5) {
                HStack {
                    Text("咀嚼概率")
                        .font(.caption)
                        .foregroundColor(.secondary)
                    Spacer()
                    Text(String(format: "%.1f%%", detector.chewingProbability * 100))
                        .font(.caption)
                        .fontWeight(.bold)
                }
                
                ProgressView(value: detector.chewingProbability)
                    .tint(detector.isChewing ? .green : .orange)
                    .scaleEffect(x: 1, y: 2, anchor: .center)
            }
            
            // 缓冲区进度
            VStack(alignment: .leading, spacing: 5) {
                HStack {
                    Text("缓冲区")
                        .font(.caption)
                        .foregroundColor(.secondary)
                    Spacer()
                    Text("\(detector.bufferFilled)%")
                        .font(.caption)
                        .fontWeight(.bold)
                }
                
                ProgressView(value: Double(detector.bufferFilled) / 100.0)
                    .tint(.blue)
                    .scaleEffect(x: 1, y: 2, anchor: .center)
            }
        }
        .padding()
        .background(Color(.systemBackground))
        .cornerRadius(15)
        .shadow(radius: 5)
    }
    
    /// 统计信息卡片
    private var statisticsCard: some View {
        VStack(spacing: 10) {
            Text("检测统计")
                .font(.headline)
                .frame(maxWidth: .infinity, alignment: .leading)
            
            Divider()
            
            // 咀嚼动作计数（突出显示）
            VStack(spacing: 8) {
                HStack {
                    Image(systemName: "fork.knife.circle.fill")
                        .font(.system(size: 24))
                        .foregroundColor(.green)
                    Text("咀嚼动作计数")
                        .font(.subheadline)
                        .foregroundColor(.secondary)
                    Spacer()
                }
                
                Text("\(detector.chewingActionCount)")
                    .font(.system(size: 48, weight: .bold, design: .rounded))
                    .foregroundColor(.green)
                    .frame(maxWidth: .infinity)
                    .padding(.vertical, 8)
                    .background(
                        RoundedRectangle(cornerRadius: 12)
                            .fill(Color.green.opacity(0.1))
                    )
            }
            
            Divider()
            
            HStack {
                StatItem(title: "总预测次数", value: "\(detector.predictionCount)")
                Divider()
                StatItem(title: "样本数", value: "\(sensorRecorder.sampleCount)")
            }
            .frame(height: 50)
        }
        .padding()
        .background(Color(.systemBackground))
        .cornerRadius(15)
        .shadow(radius: 5)
    }
    
    /// 传感器数据卡片
    private var sensorDataCard: some View {
        VStack(spacing: 10) {
            Text("实时传感器数据")
                .font(.headline)
                .frame(maxWidth: .infinity, alignment: .leading)
            
            Divider()
            
            // 加速度
            VStack(spacing: 5) {
                Text("加速度 (m/s²)")
                    .font(.caption)
                    .foregroundColor(.secondary)
                
                HStack(spacing: 15) {
                    SensorValue(axis: "X", value: sensorRecorder.currentAccX, color: .red)
                    SensorValue(axis: "Y", value: sensorRecorder.currentAccY, color: .green)
                    SensorValue(axis: "Z", value: sensorRecorder.currentAccZ, color: .blue)
                }
            }
            
            Divider()
            
            // 陀螺仪
            VStack(spacing: 5) {
                Text("陀螺仪 (rad/s)")
                    .font(.caption)
                    .foregroundColor(.secondary)
                
                HStack(spacing: 15) {
                    SensorValue(axis: "X", value: sensorRecorder.currentGyroX, color: .red)
                    SensorValue(axis: "Y", value: sensorRecorder.currentGyroY, color: .green)
                    SensorValue(axis: "Z", value: sensorRecorder.currentGyroZ, color: .blue)
                }
            }
        }
        .padding()
        .background(Color(.systemBackground))
        .cornerRadius(15)
        .shadow(radius: 5)
    }
    
    /// 控制按钮
    private var controlButtons: some View {
        VStack(spacing: 15) {
            // 开始/停止按钮
            Button(action: toggleRecording) {
                HStack {
                    Image(systemName: isRecording ? "stop.circle.fill" : "play.circle.fill")
                        .font(.title2)
                    Text(isRecording ? "停止检测" : "开始检测")
                        .font(.headline)
                }
                .frame(maxWidth: .infinity)
                .padding()
                .background(isRecording ? Color.red : Color.green)
                .foregroundColor(.white)
                .cornerRadius(10)
            }
            
            // 重置按钮
            Button(action: resetDetector) {
                HStack {
                    Image(systemName: "arrow.counterclockwise.circle.fill")
                        .font(.title2)
                    Text("重置")
                        .font(.headline)
                }
                .frame(maxWidth: .infinity)
                .padding()
                .background(Color.orange)
                .foregroundColor(.white)
                .cornerRadius(10)
            }
            .disabled(isRecording)
        }
    }
    
    /// 实时图表
    private var realtimeCharts: some View {
        VStack(spacing: 15) {
            Text("实时波形")
                .font(.headline)
                .frame(maxWidth: .infinity, alignment: .leading)
            
            // 加速度图表
            ChartView(
                title: "加速度",
                xData: sensorRecorder.accXHistory,
                yData: sensorRecorder.accYHistory,
                zData: sensorRecorder.accZHistory
            )
            .frame(height: 150)
            
            // 陀螺仪图表
            ChartView(
                title: "陀螺仪",
                xData: sensorRecorder.gyroXHistory,
                yData: sensorRecorder.gyroYHistory,
                zData: sensorRecorder.gyroZHistory
            )
            .frame(height: 150)
        }
        .padding()
        .background(Color(.systemBackground))
        .cornerRadius(15)
        .shadow(radius: 5)
    }
    
    // MARK: - 方法
    
    /// 开始/停止录制
    private func toggleRecording() {
        if isRecording {
            // 停止
            sensorRecorder.stop()
            isRecording = false
        } else {
            // 检查AirPods
            if !sensorRecorder.isDeviceMotionAvailable {
                alertMessage = "请连接支持的AirPods (Pro/3代/Max)\n并授权运动与健身权限"
                showAlert = true
                return
            }
            
            // 开始（采用训练时的采样率 25Hz）
            sensorRecorder.start(rateHz: 25)
            isRecording = true
        }
    }
    
    /// 重置检测器
    private func resetDetector() {
        detector.reset()
        sensorRecorder.rawSamples.removeAll()
        sensorRecorder.sampleCount = 0
        alertMessage = "检测器已重置"
        showAlert = true
    }
    
    /// 处理新样本
    private func processNewSample() {
        detector.processSample(
            ax: sensorRecorder.currentAccX,
            ay: sensorRecorder.currentAccY,
            az: sensorRecorder.currentAccZ,
            wx: sensorRecorder.currentGyroX,
            wy: sensorRecorder.currentGyroY,
            wz: sensorRecorder.currentGyroZ
        )
    }
}

// MARK: - 辅助视图组件

/// 统计项
struct StatItem: View {
    let title: String
    let value: String
    
    var body: some View {
        VStack(spacing: 5) {
            Text(value)
                .font(.title2)
                .fontWeight(.bold)
            Text(title)
                .font(.caption)
                .foregroundColor(.secondary)
        }
        .frame(maxWidth: .infinity)
    }
}

/// 传感器数值
struct SensorValue: View {
    let axis: String
    let value: Double
    let color: Color
    
    var body: some View {
        VStack(spacing: 3) {
            Text(axis)
                .font(.caption2)
                .foregroundColor(color)
                .fontWeight(.bold)
            Text(String(format: "%.3f", value))
                .font(.caption)
                .monospacedDigit()
        }
        .frame(maxWidth: .infinity)
    }
}

/// 简单图表视图
struct ChartView: View {
    let title: String
    let xData: [Double]
    let yData: [Double]
    let zData: [Double]
    
    var body: some View {
        VStack(alignment: .leading, spacing: 5) {
            Text(title)
                .font(.caption)
                .foregroundColor(.secondary)
            
            GeometryReader { geometry in
                ZStack {
                    // 背景
                    Rectangle()
                        .fill(Color(.systemGray6))
                    
                    // 零线
                    Path { path in
                        let midY = geometry.size.height / 2
                        path.move(to: CGPoint(x: 0, y: midY))
                        path.addLine(to: CGPoint(x: geometry.size.width, y: midY))
                    }
                    .stroke(Color.gray.opacity(0.3), lineWidth: 1)
                    
                    // X轴
                    drawLine(data: xData, color: .red, geometry: geometry)
                    
                    // Y轴
                    drawLine(data: yData, color: .green, geometry: geometry)
                    
                    // Z轴
                    drawLine(data: zData, color: .blue, geometry: geometry)
                }
            }
        }
    }
    
    private func drawLine(data: [Double], color: Color, geometry: GeometryProxy) -> some View {
        Path { path in
            guard !data.isEmpty else { return }
            
            let maxVal = data.map(abs).max() ?? 1.0
            let scale = geometry.size.height / (2.0 * max(maxVal, 0.1))
            let width = geometry.size.width
            let step = width / CGFloat(max(data.count - 1, 1))
            
            for (i, value) in data.enumerated() {
                let x = CGFloat(i) * step
                let y = geometry.size.height / 2 - CGFloat(value) * scale
                
                if i == 0 {
                    path.move(to: CGPoint(x: x, y: y))
                } else {
                    path.addLine(to: CGPoint(x: x, y: y))
                }
            }
        }
        .stroke(color, lineWidth: 1.5)
    }
}

// MARK: - 预览

struct RealtimeTestView_Previews: PreviewProvider {
    static var previews: some View {
        RealtimeTestView()
    }
}
